package leetcode.code013;

public class Solution3 implements IRomanToInteger {
	public static void main(String[] args) {
		String case1 = "III";
		String case2 = "IV";
		String case3 = "IX";
		String case4 = "LVIII";
		String case5 = "MCMXCIV";
		String case6 = "D";

		int result1 = 3;
		int result2 = 4;
		int result3 = 9;
		int result4 = 58;
		int result5 = 1994;
		int result6 = 500;

		myPrint(case1, result1, new Solution3());
		myPrint(case2, result2, new Solution3());
		myPrint(case3, result3, new Solution3());
		myPrint(case4, result4, new Solution3());
		myPrint(case5, result5, new Solution3());
		myPrint(case6, result6, new Solution3());
	}

	public static void myPrint(String s, int expect, IRomanToInteger isolution) {
		int result = isolution.romanToInt(s);
		System.out.println("字符串：" + s + " 预期：" + expect + " 结果：" + result + " " + (expect == result));
	}

	@Override
	public int romanToInt(String s) {
		if (s.length() == 1) {
			return getValue(s.charAt(0));
		}
		int result = 0;
		int pre = getValue(s.charAt(0)); // 第一个数
		int now = 0;
		for (int i = 1; i < s.length(); i++) {
			now = getValue(s.charAt(i));
			if (pre >= now) {
				result += pre;
			} else {
				result -= pre;
			}
			pre = now;
		}
		result += pre; // getValue(s.charAt(s.length()-1))
		return result;
	}

	private int getValue(char ch) {
		switch (ch) {
		case 'I':
			return 1;
		case 'V':
			return 5;
		case 'X':
			return 10;
		case 'L':
			return 50;
		case 'C':
			return 100;
		case 'D':
			return 500;
		case 'M':
			return 1000;
		default:
			return 0;
		}
	}

}
